package com.sxfq.loansupermarket.backsystem.config.web;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * ehcache配置
 *
 * @author fengshuonan
 * @date 2017-05-20 23:11
 */
@Configuration
@EnableCaching
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }

    private static Queue<Session> sessionSet = new ConcurrentLinkedQueue<Session>();

    @OnMessage
    public void onMessage(String message, Session currentSession) {
        System.out.println("Server say：Received: " + message);
        try {
            final Set<Session> sessions = currentSession.getOpenSessions();
            // 客户端互相发送消息
            for (Session session : sessions) {
                session.getBasicRemote().sendText(message);
            }
            /************ 启动定时公告 **************/
            //SystemTimer.getInstance();
            /**************************/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnOpen
    public void onOpen(Session currentSession) {
        if (sessionSet.contains(currentSession) == false) {
            sessionSet.add(currentSession);
            System.out.println("WebSocketTest.onOpen()================Add=" + sessionSet.size());
        }
        System.out.println("Server say：Client connected");
    }

    @OnClose
    public void onClose(Session currentSession) {
        if (sessionSet.contains(currentSession)) {
            sessionSet.remove(currentSession);
        }
        System.out.println("Server say：Connection closed============Close=" + sessionSet.size());
    }

    public static Queue<Session> getSessionSet() {
        return sessionSet;
    }
}